package com.bezdelnick.forum.validator;

import com.bezdelnick.forum.service.ForumService;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 21.08.12
 * Time: 14:09
 * To change this template use File | Settings | File Templates.
 */
public class UserExistValidator implements IValidator<String> {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserExistValidator.class);

    @SpringBean
    @SuppressWarnings("unused")
    private ForumService forumService;

    public UserExistValidator() {
        super();
        /* Add this instance to Spring context */
        SpringComponentInjector.get().inject(this);
    }


    @Override
    public void validate(IValidatable<String> validatable) {
        try {
            String username = validatable.getValue();
            if (forumService.getAppUserDao().getUserByName(username) != null) {
                addError(validatable, "name_exists");
            }
        } catch (Exception ex) {
            LOGGER.warn(ex.getMessage());
        }
    }

    private void addError(IValidatable<String> validatable, String errorKey) {
        ValidationError error = new ValidationError();
        error.addMessageKey(getClass().getSimpleName() + "." + errorKey);
        validatable.error(error);
    }
}
